﻿$(document).ready(Page_Load);

var rowdata;
var alertdata;
var currentid;

function Page_Load(e) {
    LoadGrid();
    $('.button').button();

    $('[name="btnNewProject"]').click(function () {
        $("#dialog-newproject").dialog({
            resizable: false,
            height: 320,
            width: 505,
            modal: true,
            buttons: {
                'Create': function () {
                    CreateProject();
                },
                'Cancel': function () {
                    $(this).dialog('close');
                }
            },
            close: function () {
                $('input').val("");

                $(".error-container").removeClass("ui-state-error ui-corner-all");
                $(".error").html("");

                $('input').removeClass("ui-state-error");
            }
        });
    });
}

function CreateProject() {
    var projectname = $('#name');
    var projectdescription = $('#description');

    var webMethodParams = JSON.stringify({ ProjectName: projectname.val(), ProjectDescription: projectdescription.val() });

    var bValid = true;

    bValid = bValid && checkLength(projectname, "Project Name", 5);
   
    if (bValid) {
        $.ajax(
            {
                type: "POST",
                async: true,
                url: "Home.aspx/CreateProject",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: webMethodParams,
                success: RefreshGrid,
                error: Command_Error
            });

        
    }
}

function LoadGrid() {

    $("#list2").jqGrid(
        {
            datatype: "local",
            colNames: ['', '', 'Project', 'Active', ''],
            colModel: [
                { name: 'act', index: 'act', width: 150, sortable: false, align: 'center' },
                { name: 'id', index: 'id', width: 55, search: false, hidden: true, editable: false },
   		        { name: 'ProjectLink', index: 'Name', width: 300, editable: false },
                { name: 'ActiveInd', index: 'ActiveInd', width: 45, align: 'center', formatter: ButtonBoxFormatter, edittype: "checkbox", editable: true },
   		        { name: 'act2', index: 'act2', width: 38, sortable: false }
            ],
            rowNum: 10,
            rowList: [10, 20, 30],
            pager: '#pager2',
            sortname: 'Name',
            viewrecords: true,
            sortorder: "desc",
            caption: "Projects",
            height: 250,
            width: "100%",
            editurl: 'somepage.aspx',
            gridComplete: function () {
                var ids = $("#list2").jqGrid('getDataIDs');
                for (var i = 0; i < ids.length; i++) {
                    var cl = ids[i];

                    var data = rowdata[$("#list2").jqGrid('getInd', cl, false) - 1];

                    var emailcount = data["EmailCount"];
                    var lastemail = data["EntryDt"];

                    if (emailcount > 0) {
                        email = "<img class=\'gridaction\' src=\'/Images/mailbox_full.png\' alt=\'View Emails (" + lastemail + ")\' title=\'View Emails (" + lastemail + ")\' onclick=\"View Emails('" + cl + "');\"/>";
                    }
                    else {
                        email = "<img class=\'gridaction\' src=\'/Images/mailbox_empty.png\' alt=\'View Emails\' title=\'View Emails\' onclick=\"View Emails('" + cl + "');\"/>";
                    }

                    //                    lock = "<img class=\'gridaction\' src=\'/Images/Encrypt.png\' alt=\'Lock or Unlock\' title=\'Lock or Unlock\' onclick=\"UnlockUser('" + cl + "');\"/>";
                    activate = "<img class=\'gridaction\' src=\'/Images/base_checkmark_32.png\' alt=\'Activate/Deactivate\' title=\'Activate/Deactivate\' onclick=\"ActivateProject('" + cl + "');\"/>";
                    ed = "<img class=\'gridaction\' src=\'/Images/Page.png\' alt=\'Edit\' title=\'Edit\' onclick=\"EditProject('" + cl + "');\"/>";
                    de = "<img class=\'gridaction\' src=\'/Images/delete.png\' height=32 width=32 alt=\'Delete\' title=\'Delete\' onclick=\"DeleteProject('" + cl + "');\"/>";
                    addalert = "<img class=\'gridaction\' src=\'/Images/Users.png\' height=32 width=32 alt=\'Add Alert Email\' title=\'Add Alert Email\' onclick=\"AddEmail('" + cl + "');\"/>";
                    $("#list2").jqGrid('setRowData', ids[i], { act: activate + ed + addalert + email, act2: de });
                }
            }
        });

    $("#list2").jqGrid('navGrid', '#pager2', { edit: false, add: false, del: false, beforeRefresh: function () { GetProjects(); } })


    GetProjects();
}

function GetProjects() {

    $.ajax(
            {
                type: "POST",
                async: true,
                url: "Home.aspx/GetUsersProjects",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: LoadProjects_Success,
                error: LoadProjects_Error
            });

}

function LoadProjects_Success(data, textStatus, XMLHttpRequest) {
    rowdata = data.d;
    BindGrid($("#list2"), rowdata, "ProjectId", 1);
}

function LoadProjects_Error(XMLHttpRequest, textStatus, errorThrown) {
    Log(XMLHttpRequest, "LoadProjects", 100);
    alert("An error occurred loading the user projects. Error: " + XMLHttpRequest);

}

function GetProject(project) {

    var webMethodParams = JSON.stringify({ ProjectId: project });
    $.ajax(
            {
                type: "POST",
                async: true,
                url: "Home.aspx/GetProject",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: webMethodParams,
                success: LoadProject_Success,
                error: LoadProjects_Error
            });
}



function RefreshGrid(data, textStatus, XMLHttpRequest) {
    if (data.d == "" || data.d == null) {
        $("#dialog-newproject").dialog('close');
        GetProjects();
    }
    else {
        alert(data.d);
    }
}

function Command_Error(XMLHttpRequest, textStatus, errorThrown) {
    Log(XMLHttpRequest, "CreateProject", 100);
    alert("An error occurred creating the project. Error: " + XMLHttpRequest);

}

function ButtonBoxFormatter(cellvalue, options, rowObject) {
    switch (cellvalue) {
        case "True":
            return "<img src='/Images/green_button.png' width='20px' alt='Active' title='Active'/>";
            break;
        default:
            return "<img src='/Images/red_button.png' width='20px' alt='Inactive' title='Inactive'/>";
            break;
    }
}


function EditProject(project) {
    var data = rowdata[$("#list2").jqGrid('getInd', project, false) - 1];

    $("#name").val(data["Name"]);
    $("#description").val(data["Description"]);

    $("#dialog-newproject").dialog({
        resizable: false,
        height: 320,
        width: 505,
        modal: true,
        buttons: {
            'Update': function () {

                var data = rowdata[$("#list2").jqGrid('getInd', project, false) - 1];

                var projectname = $('#name');
                var projectdescription = $('#description');

                var webMethodParams = JSON.stringify({ ProjectId: project, ProjectName: projectname.val(), ProjectDescription: projectdescription.val(), ActiveInd: data["ActiveInd"] });

                var bValid = true;

                bValid = bValid && checkLength(projectname, "Project Name", 5);

                if (bValid) {
                    $.ajax(
                        {
                            type: "POST",
                            async: true,
                            url: "Home.aspx/UpdateProject",
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            data: webMethodParams,
                            success: RefreshGrid,
                            error: Command_Error
                        });


                }
            },
            'Cancel': function () {
                $(this).dialog('close');
            }
        },
        close: function () {
            $('input').val("");

            $(".error-container").removeClass("ui-state-error ui-corner-all");
            $(".error").html("");

            $('input').removeClass("ui-state-error");
        }
    });
}

function ActivateProject(project) {
    var data = rowdata[$("#list2").jqGrid('getInd', project, false) - 1];

    var name = data["Name"];
    var description = data["Description"];
    var active = data["ActiveInd"];

    var webMethodParams = JSON.stringify({ ProjectId: project, ProjectName: name, ProjectDescription: description, ActiveInd: active });


    
    $.ajax(
            {
                type: "POST",
                async: true,
                url: "Home.aspx/ActivateProject",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: webMethodParams,
                success: RefreshGrid,
                error: Command_Error
            });
}

function DeleteProject(project) {
    var data = rowdata[$("#list2").jqGrid('getInd', project, false) - 1];
    var $dialog = $('<div></div>')
		.html('Please confirm the delete request (' + data["Name"] + ').')
		.dialog({
		    autoOpen: false,
		    resizable: false,
		    height: 200,
		    width: 400,
		    modal: true,
		    buttons: {
		        'Yes': function () {
		            DeleteConfirmed(project);
		            $(this).dialog('close');
		        },
		        'No': function () {
		            $(this).dialog('close');
		        }
		    },
		    title: 'Confirm Delete'
		});
    $dialog.dialog('open');
}

function DeleteConfirmed(project) {
    var webMethodParams = JSON.stringify({ ProjectId: project });
    $.ajax(
            {
                type: "POST",
                async: true,
                url: "Home.aspx/DeleteProject",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: webMethodParams,
                success: RefreshGrid,
                error: Command_Error
            });
}

function AddEmail(project) {
    currentid = project;

    $("#dialog-maintainalerts").dialog({
        resizable: false,
        height: 410,
        width: 505,
        modal: true,
        buttons: {
            'Done': function () {
                $(this).dialog('close');
            }
        },
        close: function () {
            
        }
    });
   
    $("#addemail").button();
    $("#addemail").click(function () {
        InsertEmail(project);
    });

    $("#alertlist").jqGrid(
        {
            datatype: "local",
            colNames: ['', 'Email', ''],
            colModel: [
                { name: 'id', index: 'id', width: 55, search: false, hidden: true, editable: false },
   		        { name: 'Email', index: 'email', width: 350, editable: false },
                { name: 'act2', index: 'act2', width: 38, sortable: false }
            ],
            rowNum: 10,
            rowList: [10, 20, 30],
            pager: '#alertpager',
            sortname: 'Name',
            viewrecords: true,
            sortorder: "desc",
            caption: "",
            height: 145,
            width: "465",
            editurl: 'somepage.aspx',
            gridComplete: function () {
                var ids = $("#alertlist").jqGrid('getDataIDs');
                for (var i = 0; i < ids.length; i++) {
                    var cl = ids[i];
                    //                    lock = "<img class=\'gridaction\' src=\'/Images/Encrypt.png\' alt=\'Lock or Unlock\' title=\'Lock or Unlock\' onclick=\"UnlockUser('" + cl + "');\"/>";
                    //activate = "<img class=\'gridaction\' src=\'/Images/base_checkmark_32.png\' alt=\'Activate/Deactivate\' title=\'Activate/Deactivate\' onclick=\"ActivateProject('" + cl + "');\"/>";
                    //ed = "<img class=\'gridaction\' src=\'/Images/Page.png\' alt=\'Edit\' title=\'Edit\' onclick=\"EditProject('" + cl + "');\"/>";
                    de = "<img class=\'gridaction\' src=\'/Images/delete.png\' height=32 width=32 alt=\'Delete\' title=\'Delete\' onclick=\"DeleteAlertEmail('" + cl + "');\"/>";
                    //addalert = "<img class=\'gridaction\' src=\'/Images/Users.png\' height=32 width=32 alt=\'Add Alert Email\' title=\'Add Alert Email\' onclick=\"AddEmail('" + cl + "');\"/>";
                    $("#alertlist").jqGrid('setRowData', ids[i], { act2: de });
                }
            }
        });

        $("#alertlist").jqGrid('navGrid', '#alertpager', { edit: false, add: false, del: false, beforeRefresh: function () { GetAlertEmails(project); } });

        GetAlertEmails(project);
}

function GetAlertEmails(project) {
    var webMethodParams = JSON.stringify({ ProjectId: project });
    $.ajax(
            {
                type: "POST",
                async: true,
                url: "Home.aspx/GetAlertEmails",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: webMethodParams,
                success: LoadAlertEmails_Success,
                error: LoadAlertEmails_Error
            });
}

function LoadAlertEmails_Success(data, textStatus, XMLHttpRequest) {
    alertdata = data.d;
    BindGrid($("#alertlist"), alertdata, "ProjectAlertEmailId", 1);
}

function LoadAlertEmails_Error(XMLHttpRequest, textStatus, errorThrown) {
    Log(XMLHttpRequest, "LoadProjectAlertEmails", 100);
    alert("An error occurred loading the project emails. Error: " + XMLHttpRequest);
}

function RefreshAlertGrid(data, textStatus, XMLHttpRequest) {
    if (data.d == "" || data.d == null) {
        GetAlertEmails(currentid);
    }
    else {
        alert(data.d);
    }
}

function InsertEmail(project) {
    var email = $('#alertemail');
        
    var bValid = true;

    bValid = bValid && checkRegexp(email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "Enter a valid email address.  eg. user@email.com");

    bValid = bValid && checkLength(email, "email address", 6);
   
    if (bValid) {
        var webMethodParams = JSON.stringify({ ProjectId: project, Email: email.val() });
        $('#alertemail').val("");
        $.ajax(
                {
                    type: "POST",
                    async: true,
                    url: "Home.aspx/AddAlertEmails",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    data: webMethodParams,
                    success: RefreshAlertGrid,
                    error: LoadAlertEmails_Error
                });
       
    }
}

function DeleteAlertEmail(alertid) {
    var data = alertdata[$("#alertlist").jqGrid('getInd', alertid, false) - 1];
    var $dialog = $('<div></div>')
		.html('Please confirm the delete request (' + data["Email"] + ').')
		.dialog({
		    autoOpen: false,
		    resizable: false,
		    height: 200,
		    width: 400,
		    modal: true,
		    buttons: {
		        'Yes': function () {
		            DeleteAlertEmailConfirmed(alertid);
		            $(this).dialog('close');
		        },
		        'No': function () {
		            $(this).dialog('close');
		        }
		    },
		    title: 'Confirm Delete'
		});
    $dialog.dialog('open');
}

function DeleteAlertEmailConfirmed(alertid) {

    var webMethodParams = JSON.stringify({ ProjectAlertEmailId: alertid });
    $.ajax(
            {
                type: "POST",
                async: true,
                url: "Home.aspx/DeleteAlertEmails",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: webMethodParams,
                success:  RefreshAlertGrid,
                error: LoadAlertEmails_Error
            });

}

function ViewEmails(project) {

}